package com.ibeetl.cms.web;

import com.ibeetl.admin.console.web.dto.EnterpriseExcelImportData;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.HttpRequestLocal;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.Enterprise;
import com.ibeetl.cms.service.EnterpriseService;
import com.ibeetl.cms.service.EssentialInformationService;
import com.ibeetl.cms.web.query.EnterpriseQuery;
import com.ibeetl.cms.web.query2.EnterpriseMaintainQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.*;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Enterprise 接口
 */
@Controller
public class EnterpriseController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/enterprise";


    @Autowired private EnterpriseService enterpriseService;

    @Autowired private EssentialInformationService essentialInformationService;

    @Autowired
    CorePlatformService platformService;
    
    @Autowired
    FileService fileService;

    @Autowired
    CoreUserService userService;

    @Autowired
    HttpRequestLocal httpRequestLocal;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("cms.enterprise.check")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/enterprise/index.html");
        view.addObject("search", EnterpriseQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/indexMaintain.do")
    @Function("cms.enterprise.query")
    @ResponseBody
    public ModelAndView indexMaintain() {
        ModelAndView view = new ModelAndView("/cms/enterprise/indexMaintain.html") ;
        view.addObject("search", EnterpriseMaintainQuery.class.getName());
        return view;
    }


    @GetMapping(MODEL + "/essentialInformation.do")
    @Function("cms.enterprise.edit")
    @ResponseBody
    public ModelAndView essentialInformation() {
        ModelAndView view = new ModelAndView("/cms/enterprise/essentialInformation.html");
        CoreUser user = platformService.getCurrentUser();
        Enterprise enterprise = enterpriseService.findenterprise(user.getId());
        view.addObject("enterprise", enterprise);
        return view;
    }

    /**
     * 企业信息列表编辑(审核)
     * @param id
     * @return
     */
    @GetMapping(MODEL + "/edit.do")
    @Function("cms.enterprise.query")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/enterprise/essentialInformationList.html");
        Enterprise enterprise = enterpriseService.queryById (id);
        view.addObject("enterprise", enterprise);
        return view;
    }

    @GetMapping(MODEL + "/initEdit.do")
    @Function("cms.enterprise.edit")
    @ResponseBody
    public ModelAndView initEdit() {
        ModelAndView view = new ModelAndView("/cms/enterprise/initEdit.html");
        CoreUser user = platformService.getCurrentUser();
        Enterprise enterprise = enterpriseService.findenterprise(user.getId());
        view.addObject("enterprise", enterprise);

        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("cms.enterprise.query")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/enterprise/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult<PageQuery> list(EnterpriseQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        enterpriseService.queryByConditionInfo(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/listMaintain.json")//企业信息维护
    @Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult<PageQuery> listMaintain(EnterpriseQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        enterpriseService.queryByConditionMaintain(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)Enterprise enterprise)
    {
        enterpriseService.save(enterprise);
        return JsonResult.success();
    }

    @PostMapping(MODEL + "/update.json")
//    @Function("cms.enterprise.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  Enterprise enterprise) {
        if(!enterprise.getEnterpriseName().equals(enterprise.getOldEnterpriseName())){//企业信息名变跟时修改其员工的现工作企业名
            essentialInformationService.updateWorkingName(enterprise.getUserId(),enterprise.getEnterpriseName());
            userService.updateUserName(enterprise.getUserId(),enterprise.getEnterpriseName());
        }
        if(enterprise.getBusinessQuota()==null)enterpriseService.updateQuota(enterprise.getId());
        boolean success = enterpriseService.updateTemplate(enterprise);
        CoreUser user=userService.getUserById(enterprise.getUserId().longValue());
        if (success) {
            httpRequestLocal.setSessionValue(CorePlatformService.ACCESS_CURRENT_USER,user);
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    @PostMapping(MODEL + "/initEdit.json")
    @ResponseBody
    public JsonResult<String> initEdit(@Validated(ValidateConfig.UPDATE.class)  Enterprise enterprise) {
        CoreUser user = platformService.getCurrentUser();
        user.setName(enterprise.getEnterpriseName());
        //初次登录填写完基本信息 状态2
        user.setNeedInfo("2");
        userService.update(user);

        if(enterprise.getBusinessQuota()==null)enterpriseService.updateQuota(enterprise.getId());
        boolean success = enterpriseService.updateTemplate(enterprise);
        if (success) {
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult<Enterprise> queryInfo(Integer id) {
        Enterprise enterprise = enterpriseService.queryById( id);
        return  JsonResult.success(enterprise);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        enterpriseService.batchDelEnterprise(idList);
        return JsonResult.success();
    }

    @PostMapping(MODEL + "/invalid.json")
    @Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult invalid(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        enterpriseService.invalid(idList);
        return JsonResult.success();
    }

    @PostMapping(MODEL + "/excel/export.json")
    @Function("cms.enterprise.query")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response, EnterpriseQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此userService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/admin/enterprise/enterprise.xls";
        PageQuery<Enterprise> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<Enterprise> list =enterpriseService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("单位信息导出.xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("enterprises", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
    }

    @PostMapping(MODEL + "/excel/import.do")
    @Function("cms.enterprise.check")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();

        InputStream inputXML = Thread.currentThread().getContextClassLoader().getResourceAsStream("excelTemplates/admin/enterprise/enterprise_mapping.xml");
        XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
        InputStream inputXLS = ins;
        List<EnterpriseExcelImportData> dicts = new ArrayList<EnterpriseExcelImportData>();
        Map beans = new HashMap();
        beans.put("list", dicts);
        ReaderConfig.getInstance().setSkipErrors( true );
        XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
        List<XLSReadMessage>  errors = readStatus.getReadMessages();
        try {
            this.enterpriseService.batchInsert(dicts);
            return JsonResult.success();
        }catch(Exception ex) {
            return JsonResult.failMessage(ex.getMessage());
        }

    }


}
